package cn.zqy.services;

import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailService 
{
	private String fromAddress;
	private String toAddress;
	private String ccAddress;
	private String bccAddress;
	private String subject;
	private String body;
	private static final Logger log = Logger.getLogger(MailService.class.getName());

	/**
	 * @param fromAddress the fromAddress to set
	 */
	public void setFromAddress(String fromAddress)
	{
		this.fromAddress = fromAddress;
	}

	/**
	 * @return the fromAddress
	 */
	public String getFromAddress()
	{
		return fromAddress;
	}

	public void setToAddress(String toAddress) {
		this.toAddress = toAddress;
	}

	public String getToAddress() {
		return toAddress;
	}

	public void setBccAddress(String bccAddress) {
		this.bccAddress = bccAddress;
	}

	public String getBccAddress() {
		return bccAddress;
	}

	public void setCcAddress(String ccAddress) {
		this.ccAddress = ccAddress;
	}

	public String getCcAddress() {
		return ccAddress;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getSubject() {
		return subject;
	}

	public void setBody(String body) {
		this.body = body;
	}

	public String getBody() {
		return body;
	}

	/**
	 * {@link http://code.google.com/intl/zh-CN/appengine/docs/java/mail/usingjavamail.html}
	 *  
	 * @throws Exception
	 */
	public void sendMail() throws Exception
	{
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
		try
		{
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(this.fromAddress));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(this.toAddress));
			msg.setSubject(this.subject);
			Multipart mp = new MimeMultipart();
			MimeBodyPart htmlPart = new MimeBodyPart();
			htmlPart.setContent(this.body, "text/html");
			mp.addBodyPart(htmlPart);
			msg.setContent(mp);
			Transport.send(msg);
		}
		catch (AddressException e)
		{
			log.severe(e.toString());
			throw e;
		}
		catch (MessagingException e)
		{
			log.severe(e.toString());
			throw e;
		}
	}

}
